﻿using System.Collections.Generic;
using System.Linq;

using DanielVaughan;
using DanielVaughan.Services;
using DanielVaughan.UserOptionsModel;

namespace CalciumTemplateApp
{
	/// <summary>
	/// The UI logic for the option view.
	/// This class uses the <see cref="IUserOptionsService"/>
	/// to retrieve the list of options. Options may be defined anywhere in the app
	/// but most commonly they are set in the <see cref="AppSettings"/> class.
	/// </summary>
	public class OptionsViewModel : UserViewModel
	{
		public OptionsViewModel() : base(MainResources.Page_Options_Title)
		{
			LoadOptions();
			NavigatingFrom += HandleNavigatingFrom;
		}

		void HandleNavigatingFrom(object sender, System.ComponentModel.CancelEventArgs e)
		{
			SaveOptions();
		}

		void LoadOptions()
		{
			var userOptionsService = Dependency.Resolve<IUserOptionsService>();
			UserOptionGroupings = userOptionsService.UserOptionGroupings;
		}

		void SaveOptions()
		{
			if (UserOptionGroupings == null)
			{
				return;
			}

			foreach (IGrouping<IOptionCategory, IUserOptionReaderWriter> grouping 
														in UserOptionGroupings)
			{
				foreach (IUserOptionReaderWriter writer in grouping)
				{
					writer.Save();
				}
			}
		}

		IUserOptionGroupings userOptionGroupings;

		/// <summary>
		/// Gets the user option groupings. 
		/// The are groups of options split by <see cref="IOptionCategory"/>.
		/// </summary>
		public IUserOptionGroupings UserOptionGroupings
		{
			get
			{
				return userOptionGroupings;
			}
			private set
			{
				Assign(() => UserOptionGroupings, ref userOptionGroupings, value);
			}
		}
	}
}
